//
//  TextDataTool.m
//  TextDemo
//
//  Created by xuxi on 2024/7/14.
//

#import "TextDataTool.h"
#import <CoreGraphics/CoreGraphics.h>
#import <CoreText/CoreText.h>
//加粗
static BOOL isBold = NO;
//斜体
static BOOL isItalic = NO;
//字体名称
static NSString * fontName;

@implementation TextDataTool

+ (void)setFontName:(nonnull NSString *)name {
    fontName = name;
}

+ (nonnull NSString *)fontName {
    return fontName;
}

+(BOOL)isBold{
    return isBold;
}

+ (void)setBold:(BOOL)bold {
    isBold =bold;
}

+ (void)setItalic:(BOOL)italic {
    isItalic =italic;
}

+ (BOOL)isItalic {
    return isItalic;
}


+ (NSArray *)getTextDataWithStr:(NSString *)text size:(CGSize)size textHeight:(CGFloat )textHeight
{

    UIImage *image = [self getImageWithStr:text size:size textHeight:textHeight];
    // 将图像转换为一维数组
    CGImageRef cgImage = image.CGImage;
    size_t width = CGImageGetWidth(cgImage);
    size_t height = CGImageGetHeight(cgImage);

    NSLog(@"text width %zu",width);
    NSLog(@"text height %zu",height);


    size_t bytesPerPixel = 4; // RGBA
    size_t bytesPerRow = bytesPerPixel * width;
    size_t bitsPerComponent = 8;

    void *data = malloc(height * bytesPerRow);
    // 清空脏数据
    for (int i = 0; i < height * bytesPerRow; i++) {
        char *bytes = (char *)data;
        bytes[i] = 0;
    }
    CGContextRef bitmapContext = CGBitmapContextCreate(data,
                                                       width,
                                                       height,
                                                       bitsPerComponent,
                                                       bytesPerRow,
                                                       CGImageGetColorSpace(cgImage),
                                                       kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

    CGContextDrawImage(bitmapContext, CGRectMake(0, 0, width, height), cgImage);

    // 释放资源
    //CGImageRelease(cgImage);
    CGContextRelease(bitmapContext);

    // 转换为一维数组
    NSMutableArray *array = [NSMutableArray array];


    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            unsigned char *pixel = ((unsigned char *) data + y * bytesPerRow + x *bytesPerPixel);
            if (pixel[3] > 0) { // 如果像素不透明
                [array addObject:@(1)];
            } else {
                [array addObject:@(0)];
            }
        }
    }



    /*for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            unsigned char *pixel = ((unsigned char *) data + y * bytesPerPixel + x *bytesPerRow );

            //NSLog(@"text a %hhu",pixel[3]);
            if (pixel[3] > 0) { // 如果像素不透明
                [array addObject:@(1)];
            } else {
                [array addObject:@(0)];
            }
        }
    }*/

    free(data);

    return array;
}



+ (UIImage *)getImageWithStr:(NSString *)str size:(CGSize)size textHeight:(CGFloat )textHeight
{

    // 设置文本属性
    NSDictionary *textAttributes ;

    UIFont *font;
    if (fontName == nil || [fontName isEqualToString:@""]) {
        //使用系统默认字体
        if(isBold && isItalic){
            UIFont *regularFont = [UIFont systemFontOfSize:textHeight];
            UIFontDescriptor *italicDescriptor = [regularFont.fontDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitItalic];
            UIFontDescriptor *boldItalicDescriptor = [italicDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold];
            font = [UIFont fontWithDescriptor:boldItalicDescriptor size:textHeight];
        }else if(isBold){
            // 设置粗体
            font = [UIFont boldSystemFontOfSize:textHeight];
        }else if(isItalic){
            // 设置斜体
            font = [UIFont italicSystemFontOfSize:textHeight];
        }
    }else{
        font = [UIFont fontWithName:fontName size:textHeight];
    }

    if(font == nil){
        textAttributes = @{
                NSForegroundColorAttributeName: [UIColor blackColor]
        };
    }else{
        textAttributes = @{
                NSFontAttributeName: font, // 替换为需要的字体：font、boldFont、italicFont 或 boldItalicFont
                NSForegroundColorAttributeName: [UIColor blackColor]
        };
    }



    // 计算文本的大小并居中
    CGSize textSize = [str sizeWithAttributes:textAttributes];


    // 创建图形上下文 你好自己
    if(size.width == -1){
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(textSize.width, size.height), NO, 1);
    }else{
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width, size.height), NO, 1);
    }




    // 获取当前上下文
    CGContextRef context = UIGraphicsGetCurrentContext();


    // 设置抗锯齿关闭
    CGContextSetShouldAntialias(context, NO);


    NSLog(@"text width1 %f",textSize.width);
    CGFloat x = 0;
    CGFloat y = (size.height - textSize.height) / 2;
    if(textSize.height == 12){
        y = y-1;
    }

    CGPoint textPoint = CGPointMake(x, y);

    //NSLog(@"size.height: %f", size.height);
    //NSLog(@"textSize.height: %f", textSize.height);

    // 绘制文本
    [str drawAtPoint:textPoint withAttributes:textAttributes];

    // 获取图像
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    // 结束上下文
    UIGraphicsEndImageContext();

    return image;
}

@end
